<?php

class Core_Backend_Component_Subject_Controller_Category extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'id', $dir = 'asc', $areaid = 0) {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('subject/collection_category');
        $dir == 'asc' ? $collection->orderby()->asc($sort) : $collection->orderby()->desc($sort);
        if ($validator->isNotEmpty('title')) {
            $collection->where()->like('title', ':title:s')->closest()
                    ->addParameter('title', '%' . $validator->getValue('title') . '%');
        }
        $collection->joinTheme()->pagination($pageindex, $pagesize)->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        $categories = App::getModel('subject/collection_category')->load();
        $themes = App::getModel('design/collection_page_theme')
                        ->filterByType('subject')
                        ->filterByEnabled(1)
                        ->load();
        return $this->viewResult(array('parent_categories' => $categories, 'themes' => $themes));
    }

    public function editAction($id) {
        $model = App::getModel('subject/category')->load($id);
        $result = $this->createAction();
        $result->getParentCategories()->removeItemById($model->getId());
        return $result->setModel($model);
    }

    public function applyPostAction() {
        return $this->savePostAction(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

    private function saveModel($return = TRUE) {
        $data = $this->getRequest()->getForm('category');

        $model = App::getModel('subject/category');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{subject.label.category}', $model->getName()));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('subject/category/index')) :
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{subject.label.category}', $model->getTitle()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}